package com.garlicts.framework.binlog.sync.listener;

import org.springframework.context.ApplicationListener;

import com.alibaba.otter.canal.protocol.CanalEntry.Entry;
import com.alibaba.otter.canal.protocol.CanalEntry.RowChange;
import com.alibaba.otter.canal.protocol.CanalEntry.RowData;
import com.garlicts.framework.binlog.sync.event.CanalEvent;
import com.google.protobuf.InvalidProtocolBufferException;

public abstract class CanalListener<EVENT extends CanalEvent> implements ApplicationListener<EVENT> {

	@Override
	public void onApplicationEvent(EVENT event) {

		Entry entry = event.getEntry();
		String databaseName = entry.getHeader().getSchemaName();
		String tableName = entry.getHeader().getTableName();
		
		try {
			RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
			rowChange.getRowDatasList().forEach(rowData -> doSync(databaseName, tableName, rowData));
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		
	}
	
	public abstract void doSync(String databaseName, String tableName, RowData rowData);
	
}
